package cn.hbnu.web.servlet;

import cn.hbnu.dao.StudentDao;
import cn.hbnu.domain.Student;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.设置字符编码
        request.setCharacterEncoding("utf-8");
        // 2.获取用户输入的信息
        String sname = request.getParameter("sname");
        String password = request.getParameter("password");
//        System.out.println(userName+"   "+password);
        // 3.将获取的用户登录信息封装到Student 类的参数对象中
        Student loginstu = new Student();
        loginstu.setSname(sname);
        loginstu.setPassword(password);

        // 4.调用 dao 中的用户登录的方法
        Student stu = new StudentDao().login(loginstu);

        // 5.判断用户是否登录成功
        if(stu != null){ // 登录成功
            // 将登录成功的所有用户信息保存到 request 对象的属性中
            request.setAttribute("stu2",stu);

            // 页面转发至主页面
            RequestDispatcher dis = request.getRequestDispatcher("/success.jsp");
            dis.forward(request,response);
        } else { //登录失败
            request.setAttribute("error","用户名或密码错误！");

            // 页面转发至用户登录页面
            RequestDispatcher dis = request.getRequestDispatcher("/index.jsp");
            dis.forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
